"""
Docmee API Verification Script
Verify docmee (AIPPT) API functionality using native API calls
"""
import os
import requests
import json
import time
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# API Configuration
AIPPT_TOKEN = os.getenv("AIPPT_TOKEN")
AIPPT_BASE_URL = os.getenv("AIPPT_BASE_URL", "https://open.docmee.cn/api")

def print_section(title):
    """Print section header"""
    print("\n" + "="*60)
    print(f"  {title}")
    print("="*60)

def print_result(success, message, data=None):
    """Print test result"""
    status = "[PASS]" if success else "[FAIL]"
    print(f"{status} {message}")
    if data:
        print(f"Data: {json.dumps(data, indent=2, ensure_ascii=False)}")

class DocmeeAPIVerifier:
    """Docmee API verification class"""

    def __init__(self, token, base_url):
        self.token = token
        self.base_url = base_url
        # Use token header for most APIs (can also use Api-Key header)
        self.headers = {
            "token": token,
            "Content-Type": "application/json"
        }
        # For some endpoints that specifically require Api-Key header
        self.api_key_headers = {
            "Api-Key": token
        }

    def test_connection(self):
        """Test basic API connection"""
        print_section("Test 1: API Connection Test")
        try:
            # Test by getting options
            url = f"{self.base_url}/ppt/v2/options"
            response = requests.get(url, headers=self.headers, timeout=30)

            if response.status_code == 200:
                data = response.json()
                print_result(True, "API connection successful", data)
                return True, data
            else:
                print_result(False, f"API connection failed: {response.status_code}",
                           {"status_code": response.status_code, "body": response.text})
                return False, None
        except Exception as e:
            print_result(False, f"Connection error: {str(e)}")
            return False, None

    def test_get_options(self):
        """Test getting generation options"""
        print_section("Test 2: Get Generation Options")
        try:
            url = f"{self.base_url}/ppt/v2/options"
            response = requests.get(url, headers=self.headers, timeout=30)

            if response.status_code == 200:
                data = response.json()
                if data.get("code") == 0:
                    print_result(True, "Successfully retrieved options", data.get("data"))
                    return True, data.get("data")
                else:
                    print_result(False, f"API returned error: {data.get('message')}", data)
                    return False, None
            else:
                print_result(False, f"Request failed: {response.status_code}",
                           {"status_code": response.status_code, "body": response.text})
                return False, None
        except Exception as e:
            print_result(False, f"Error: {str(e)}")
            return False, None

    def test_get_template_options(self):
        """Test getting template filter options"""
        print_section("Test 3: Get Template Filter Options")
        try:
            url = f"{self.base_url}/ppt/template/options"
            response = requests.get(url, headers=self.headers, timeout=30)

            if response.status_code == 200:
                data = response.json()
                if data.get("code") == 0:
                    print_result(True, "Successfully retrieved template options", data.get("data"))
                    return True, data.get("data")
                else:
                    print_result(False, f"API returned error: {data.get('message')}", data)
                    return False, None
            else:
                print_result(False, f"Request failed: {response.status_code}",
                           {"status_code": response.status_code, "body": response.text})
                return False, None
        except Exception as e:
            print_result(False, f"Error: {str(e)}")
            return False, None

    def test_get_templates(self, page=1, page_size=5):
        """Test getting PPT templates"""
        print_section("Test 4: Get PPT Templates")
        try:
            url = f"{self.base_url}/ppt/templates"
            payload = {
                "page": page,
                "pageSize": page_size
            }
            response = requests.post(url, headers=self.headers, json=payload, timeout=30)

            if response.status_code == 200:
                data = response.json()
                if data.get("code") == 0:
                    result_data = data.get("data", {})
                    templates = result_data.get("list", [])
                    total = result_data.get("total", 0)
                    print_result(True, f"Successfully retrieved {len(templates)} templates (total: {total})",
                               {"total": total, "templates_count": len(templates),
                                "first_template": templates[0] if templates else None})
                    return True, templates
                else:
                    print_result(False, f"API returned error: {data.get('message')}", data)
                    return False, None
            else:
                print_result(False, f"Request failed: {response.status_code}",
                           {"status_code": response.status_code, "body": response.text})
                return False, None
        except Exception as e:
            print_result(False, f"Error: {str(e)}")
            return False, None

    def test_create_task(self, task_type=1, content="Test PPT about artificial intelligence"):
        """Test creating a PPT generation task"""
        print_section("Test 5: Create PPT Task")
        try:
            url = f"{self.base_url}/ppt/v2/createTask"

            # Using multipart/form-data
            headers_without_content_type = {
                "token": self.token
            }

            files = {
                'type': (None, str(task_type)),
                'content': (None, content)
            }

            response = requests.post(url, headers=headers_without_content_type,
                                   files=files, timeout=30)

            if response.status_code == 200:
                data = response.json()
                if data.get("code") == 0:
                    task_data = data.get("data", {})
                    task_id = task_data.get("taskId")
                    print_result(True, f"Successfully created task: {task_id}", task_data)
                    return True, task_id
                else:
                    print_result(False, f"API returned error: {data.get('message')}", data)
                    return False, None
            else:
                print_result(False, f"Request failed: {response.status_code}",
                           {"status_code": response.status_code, "body": response.text})
                return False, None
        except Exception as e:
            print_result(False, f"Error: {str(e)}")
            return False, None

    def test_api_info(self):
        """Test getting API info (credit balance)"""
        print_section("Test 6: Get API Info (Credits)")
        try:
            url = f"{self.base_url}/user/apiInfo"
            # Use Api-Key header for this endpoint (as per documentation)
            response = requests.get(url, headers=self.api_key_headers, timeout=30)

            if response.status_code == 200:
                data = response.json()
                if data.get("code") == 0:
                    print_result(True, "Successfully retrieved API info", data.get("data"))
                    return True, data.get("data")
                else:
                    print_result(False, f"API returned error: {data.get('message')}", data)
                    return False, None
            else:
                print_result(False, f"Request failed: {response.status_code}",
                           {"status_code": response.status_code, "body": response.text})
                return False, None
        except Exception as e:
            print_result(False, f"Error: {str(e)}")
            return False, None

def main():
    """Main verification function"""
    print("\n" + "*"*60)
    print("  Docmee API Verification Test")
    print("*"*60)

    # Check token configuration
    if not AIPPT_TOKEN or AIPPT_TOKEN.startswith("your_"):
        print("\n[ERROR] AIPPT_TOKEN not configured in .env file")
        return

    print(f"\nBase URL: {AIPPT_BASE_URL}")
    print(f"Token: {AIPPT_TOKEN[:20]}...")

    # Initialize verifier
    verifier = DocmeeAPIVerifier(AIPPT_TOKEN, AIPPT_BASE_URL)

    # Run tests
    results = []

    # Test 1: Connection
    success, _ = verifier.test_connection()
    results.append(("Connection Test", success))

    if not success:
        print("\n[ERROR] Basic connection failed. Please check token and network.")
        return

    # Test 2: Get Options
    success, options = verifier.test_get_options()
    results.append(("Get Options", success))

    # Test 3: Get Template Options
    success, template_options = verifier.test_get_template_options()
    results.append(("Get Template Options", success))

    # Test 4: Get Templates
    success, templates = verifier.test_get_templates()
    results.append(("Get Templates", success))

    # Test 5: Create Task
    success, task_id = verifier.test_create_task()
    results.append(("Create Task", success))

    # Test 6: Get API Info
    success, api_info = verifier.test_api_info()
    results.append(("Get API Info", success))

    # Print summary
    print_section("Test Summary")
    passed = sum(1 for _, success in results if success)
    total = len(results)

    for test_name, success in results:
        status = "[PASS]" if success else "[FAIL]"
        print(f"{status} {test_name}")

    print(f"\nTotal: {passed}/{total} tests passed")

    if passed == total:
        print("\n[SUCCESS] All tests passed! Docmee API is working correctly.")
    else:
        print(f"\n[WARNING] {total - passed} test(s) failed. Please check the errors above.")

if __name__ == "__main__":
    main()
